<?php
/**
 * Created by PhpStorm.
 * User: zskj
 * Date: 2019/2/22
 * Time: 16:39
 */

namespace app\tools;

class MIniprogram
{
    static function code2session($code, $wechat=[]){

        if(!$wechat){
            $wechat = [
                'appid' => config('mini.appid'),
                'secret' => config('mini.secret'),
            ];
        }

        $appid = $wechat['appid'];
        $secret = $wechat['secret'];

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";

        $result = curl($url);
        $result = json_decode($result, true);

        if($result['errcode'] > 0){
            echo fail();die();
        }

        return [
            'openid'=> $result['openid'],
            'unionid'=> $result['unionid']?:'',
            'session_key'=> $result['session_key'],
        ];

    }

    static function decryptData($appid, $sessionKey, $iv, $encryptedData){

        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if($errCode == 0){
            $data = json_decode($data, true);
            return [
                'openid'=> $data['openId'],
                'nickname'=> $data['nickName'],
                'gender'=> $data['gender'],
                'language'=> $data['language'],
                'city'=> $data['city'],
                'province'=> $data['province'],
                'country'=> $data['country'],
                'avatar_url'=> $data['avatarUrl'],
                'unionid'=> $data['unionId']?:'',
            ];
        }else{
            exit(fail());
        }
    }

    // 获取accesstoken
    static function accessToken($wechat = []){

        if(!$wechat){
            $wechat = [
                'appid' => config('mini.appid'),
                'secret' => config('mini.secret'),
            ];
        }

        $redis = RedisCache::getInstance();

        $key = 'wx_accessToken_'.$wechat['appid'];
        $accessToken = $redis->get($key);

        if(!$accessToken){
            $appid = $wechat['appid'];
            $secret = $wechat['secret'];

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";

            $result = curl($url);
            $result = json_decode($result, true);

            if(isset($result['errcode']) && $result['errcode'] > 0){
                echo fail();die();
            }

            RedisCache::getInstance()->setex($key, $result['expires_in'] - 5, $result['access_token']);

            $accessToken = $result['access_token'];
        }

        return $accessToken;

    }

    // 发送模版消息
    static function sendTemplate($param, $wechat=[]){

        $accessToken = self::accessToken($wechat);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$accessToken";

        $data = [
            'touser'=> $param['openid'],
            'template_id'=> $param['template_id'],
            'page'=> $param['page']?:'',
            'form_id'=> $param['form_id'],
            'data'=> $param['data'],
        ];

        $result = curl($url, json_encode($data));

        $result = json_decode($result, true);
        if($result['errcode']==0){
            return true;
        }else{
            return false;
        }
    }

    // 生成小程序码

    static function createCodeImg($code = '', $wechat = []){

        $accessToken = self::accessToken($wechat);

        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$accessToken";

        $data = curl($url, json_encode([
            "scene"=> "code=".$code,
            "page"=> "pages/new_index/index"
        ]));

        $result = json_decode($data, true);

        if($result['errcode'] != 0){
            return false;
        }

        return save_img($data, 'promo');

    }

    // 生成小程序二维码

    static function createCodeImg2($code = '', $wechat = []){

        $accessToken = self::accessToken($wechat);

        $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$accessToken";

        $data = curl($url, json_encode([
            "path"=> "pages/new_index/index?code=".$code
        ]));

        $result = json_decode($data, true);

        if($result['errcode'] != 0){
            return false;
        }

        return save_img($data, 'promo');

    }

    static function createCodeImg3($path, $query, $wechat = []){

//        echo $query;
//        Log::writeLog( $query);
        $accessToken = self::accessToken($wechat);

        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$accessToken";

        $data = curl($url, json_encode([
            "page"=> $path,
            "scene"=> $query,
        ]));
//        echo $data;
//        Log::writeLog($data);
        $result = json_decode($data, true);

        if($result['errcode'] != 0){
            return false;
        }

        return save_img($data, 'promo');

    }

    static function uploadImage($path)
    {
        $access_token = MIniprogram::accessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=image";
        $data = curl($url, [
            'media'=> curl_file_create(realpath($path))
        ]);
        $data = json_decode($data, true);
        return $data['media_id'];
    }
}